package com.example.tourpal;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.XmlResourceParser;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;

import com.example.tourpal.model.LocalDataLoader;
import com.example.tourpal.model.LocalDataLoader.PlaceRequestLishenter;
import com.example.tourpal.widget.ExpandableList;
import com.example.tourpal.widget.SpotExpandableAdapter;

public class SpotOverViewActivity extends Activity {

	public static final int RESULT_BACK = 9;

	private Context context;

	private ImageView backBt;
	private LinearLayout placeSwitch;
	private TextView citySwitch;
	private TextView spotSwitch;

	private SearchView spotSearch;

	private GridLayout hotSpotList;
	private ExpandableListView cityList;
	private SpotExpandableAdapter spotExpandableAdapter;
	private ExpandableList parseExpandableList;
	private LinearLayout spotList;

	private XmlResourceParser xmlParser;

	private int spotId;
	private boolean isSpot;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.spot_browse_viewpage);

		spotId = getIntent().getIntExtra("spotId", 0);

		context = this;

		backBt = (ImageView) findViewById(R.id.back);
		placeSwitch = (LinearLayout) findViewById(R.id.spotSwitch);
		citySwitch = (TextView) findViewById(R.id.city);
		spotSwitch = (TextView) findViewById(R.id.spot);

		spotSearch = (SearchView) findViewById(R.id.spotSearch);
		try {
			Class<?> argClass = spotSearch.getClass();
			Field mSearchHintIconField = argClass
					.getDeclaredField("mSearchHintIcon");
			mSearchHintIconField.setAccessible(true);
			ImageView mSearchHintIcon = (ImageView) mSearchHintIconField
					.get(spotSearch);
			mSearchHintIcon.setVisibility(View.VISIBLE);

			Field ownField = argClass.getDeclaredField("mSearchPlate");
			ownField.setAccessible(true);
			View mView = (View) ownField.get(spotSearch);
			mView.setBackground(context.getResources().getDrawable(
					R.drawable.search_bar_bg));

			int id = spotSearch.getContext().getResources()
					.getIdentifier("android:id/search_src_text", null, null);
			TextView textView = (TextView) spotSearch.findViewById(id);
			textView.setTextSize(15);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		hotSpotList = (GridLayout) findViewById(R.id.hotSpotList);
		cityList = (ExpandableListView) findViewById(R.id.cityList);
		spotList = (LinearLayout) findViewById(R.id.spotList);
	}

	@Override
	protected void onResume() {
		super.onResume();

		backBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});

		citySwitch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				citySwitch.setTextColor(0xff2ba47b);
				spotSwitch.setTextColor(0xffffffff);
				placeSwitch.setBackgroundResource(R.drawable.switch_right);
				cityList.setVisibility(View.VISIBLE);
				spotList.setVisibility(View.GONE);
				isSpot = false;
			}
		});

		spotSwitch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				spotSwitch.setTextColor(0xff2ba47b);
				citySwitch.setTextColor(0xffffffff);
				placeSwitch.setBackgroundResource(R.drawable.switch_left);
				cityList.setVisibility(View.GONE);
				spotList.setVisibility(View.VISIBLE);
				isSpot = true;
			}
		});

		spotSearch.setOnQueryTextListener(new OnQueryTextListener() {

			@Override
			public boolean onQueryTextSubmit(String text) {
				if (isSpot) {
					requestData(text);
				} else {
					spotExpandableAdapter = null;
					spotExpandableAdapter = new SpotExpandableAdapter(context,
							filterList(text));
					cityList.setAdapter(spotExpandableAdapter);
					spotExpandableAdapter.setSpotList(cityList);
				}
				return true;
			}

			@Override
			public boolean onQueryTextChange(String text) {
				if (!isSpot && text.trim().equals("")) {

					spotExpandableAdapter = null;
					spotExpandableAdapter = new SpotExpandableAdapter(context,
							filterList(text));
					cityList.setAdapter(spotExpandableAdapter);
					spotExpandableAdapter.setSpotList(cityList);
				}
				return true;
			}
		});

		String[] hotPlace = getResources().getStringArray(R.array.hot_places);
		for (int i = 0; i < hotPlace.length; i++) {
			TextView child = new TextView(context);
			child.setText(hotPlace[i]);
			child.setPadding(8, 8, 8, 8);
			child.setTextColor(0xff2ba47b);
			child.setTextSize(20);
			child.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					TextView tv = (TextView) v;
					setPlaceName(tv.getText().toString());
				}
			});
			hotSpotList.addView(child);
		}

		parseExpandableList = xmlLoad(R.xml.city);
		spotExpandableAdapter = new SpotExpandableAdapter(this,
				parseExpandableList);
		spotExpandableAdapter.setSpotList(cityList);
		cityList.setAdapter(spotExpandableAdapter);
		cityList.setCacheColorHint(0);
		cityList.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int pIndex, int cIndex, long id) {
				String spotSet = spotExpandableAdapter.getChild(pIndex, cIndex)
						.toString();

				Intent intent = new Intent();
				intent.putExtra("spotId", spotId);
				intent.putExtra("spotSet", spotSet);
				setResult(RESULT_BACK, intent);
				finish();
				return false;
			}
		});

	}

	protected void requestData(final String place) {
		LocalDataLoader loader = new LocalDataLoader(context);
		loader.startQueryPlaceData(place, new PlaceRequestLishenter() {

			@Override
			public void requestPlaceList(List<String> places) {
				final List<String> placeList = places;

				if (placeList.size() == 0) {
					showConfirm(place);
				} else {
					spotList.removeAllViews();
					for (int i = 0; i < placeList.size(); i++) {
						TextView child = new TextView(context);
						child.setText(placeList.get(i));
						child.setPadding(8, 8, 0, 8);
						child.setTextColor(Color.GRAY);
						child.setTextSize(30);
						child.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								TextView tv = (TextView) v;
								setPlaceName(tv.getText().toString());
							}
						});
						spotList.addView(child);
					}
				}
			}
		});
	}

	protected void showConfirm(final String place) {
		String placeConfirmHint = String.format(
				getResources().getString(R.string.place_confirm_hint), place);

		Dialog alertDialog = new AlertDialog.Builder(this)
				.setTitle(R.string.place_confirm_title)
				.setMessage(placeConfirmHint)
				.setPositiveButton(R.string.place_ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								setPlaceName(place);
							}

						})
				.setNegativeButton(R.string.place_cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								return;
							}
						}).create();
		alertDialog.show();

	}

	protected void setPlaceName(final String place) {
		Intent intent = new Intent();
		intent.putExtra("spotId", spotId);
		intent.putExtra("spotSet", place);
		setResult(RESULT_BACK, intent);
		finish();
	}

	protected ExpandableList filterList(String text) {
		ExpandableList expandableList = xmlLoad(R.xml.city);

		int size = expandableList.groupList.size();

		if (text.trim().equals("")) {

		} else {
			for (int i = 0; i < size; i++) {
				if (expandableList.groupList.get(i).indexOf(text) >= 0) {
				} else {
					int childCnt = expandableList.childList.get(i).size();
					for (int j = 0; j < childCnt; j++) {
						String chileNm = expandableList.childList.get(i).get(j);
						if (chileNm.indexOf(text) >= 0) {

						} else {
							expandableList.childList.get(i).remove(j);
							childCnt--;
							j--;
						}
					}

					if (childCnt == 0) {
						expandableList.groupList.remove(i);
						size--;
						i--;
					}
				}

			}
		}
		return expandableList;
	}

	private ExpandableList xmlLoad(int resId) {
		xmlParser = getResources().getXml(resId);

		ExpandableList expandableList = new ExpandableList();

		expandableList.groupList = new ArrayList<String>();
		expandableList.childList = new ArrayList<List<String>>();

		try {
			int eventType = xmlParser.getEventType();

			List<String> spotItem = null;

			while (eventType != XmlPullParser.END_DOCUMENT) {
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					break;
				case XmlPullParser.START_TAG:
					if (xmlParser.getName().equals("province")) {
						String provinceName = xmlParser.getAttributeValue(0);
						// Log.e("YLQ", "provinceName=" + provinceName);
						expandableList.groupList.add(provinceName);
						spotItem = new ArrayList<String>();
					} else if (xmlParser.getName().equals("item")) {
						String cityName = xmlParser.nextText();
						// Log.e("YLQ", "cityName=" + cityName);
						spotItem.add(cityName);
					}
					break;
				case XmlPullParser.END_TAG:
					if (xmlParser.getName().equals("province")) {
						expandableList.childList.add(spotItem);
					}
					break;
				default:
					break;
				}

				eventType = xmlParser.next();
			}

		} catch (Exception e) {
			// TODO: handle exception
		}

		return expandableList;
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		overridePendingTransition(R.anim.main_enter, R.anim.sub_exit);
	}

}
